package com.wdcloud.niceandroid.utils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.util.Base64;
import android.view.View;
import android.view.ViewGroup;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by lumin on 2020/11/30
 */

public class AppUtil {

    public static void openBrowser(Context context, String url) {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(context.getPackageManager()) != null) {
            final ComponentName componentName = intent.resolveActivity(context.getPackageManager());
            context.startActivity(Intent.createChooser(intent, "请选择浏览器"));
        } else {

        }
    }


    public static String compressImage(Bitmap image) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
            int options = 90;
            //Log.e("===", "===压缩结束前" + baos.toByteArray().length / 1024);

            while (baos.toByteArray().length / 1024 > (500)) {// 循环判断如果压缩后图片是否大于1024kb,大于继续压缩
                baos.reset(); // 重置baos即清空baos
                image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
                options -= 10;// 每次都减少10
            }

            byte[] bitmapBytes = baos.toByteArray();
            //Log.e("===", "===压缩结束" + bitmapBytes.length / 1024);

            return Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
        } catch (Exception e) {
            return null;
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//        return BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
    }

//    public static Bitmap decodeSampledBitmapFromResource(Context context, Bitmap originBitmap, int reqWidth, int reqHeight) {
//        BitmapFactory.Options options = new BitmapFactory.Options();
//        options.inJustDecodeBounds = true;
//        BitmapFactory.decodeByteArray()
//        BitmapFactory.decodeResource(context.getResources(), resId, options);
//        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
//        options.inJustDecodeBounds = false;
//        return BitmapFactory.decodeResource(context.getResources(), resId, options);
//    }
//    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
//        int height = options.outHeight;//获取原始图片的高度
//        int width = options.outWidth;//获取原始图片的宽度
//        int inSampleSize = 1;//设置采样率
//        if (height > reqHeight || width > reqWidth) {
//            int halfHeight = height / 2;
//            int halfWidth = width / 2;
//            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
//                inSampleSize *= 2;
//            }
//        }
//        return inSampleSize;
//    }

    public static String compressSample(byte[] data) {

        int inSampleSize = 8;//采样率设置
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inSampleSize = inSampleSize;
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);

        return compressQuality(bitmap, 100);
    }


    public static String compressSize(Bitmap bitmap) {
        int ratio = 8;//尺寸压缩比例
        Bitmap result = Bitmap.createBitmap(bitmap.getWidth() / ratio, bitmap.getHeight() / ratio, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(result);
        Rect rect = new Rect(0, 0, bitmap.getWidth() / ratio, bitmap.getHeight() / ratio);
        canvas.drawBitmap(bitmap, null, rect, null);

        return compressQuality(result, 100);
    }

    public static String compressQuality(Bitmap bitmap, int quality) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);

        byte[] bitmapBytes = baos.toByteArray();

        return Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);

//        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
//        return BitmapFactory.decodeStream(bais, null, null);//把ByteArrayInputStream数据生成图片
    }


    public static byte[] StringToByte(String strBase64) {

        byte[] bitmapArray = new byte[0];
        try {
            bitmapArray = Base64.decode(strBase64, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmapArray;
    }

    /**
     * 清楚缓存跳转登录页
     */
    public static void logOutSuccess() {
//        /**清缓存*/
//        clearCacheData();
//        /**跳转登录*/
//        Intent intent = new Intent(MyApplication.getAppContext(), LoginActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        MyApplication.getAppContext().startActivity(intent);
//        /**通知首页(MainActivity)登录退出动作,关闭MainActivity*/
//        logOutEvent();
    }

    private static void clearCacheData() {
//        UserCache.getInstance().setUserInfoBean(null);
//        UserCache.getInstance().setRealNameAuthentication(false);
//        SPDataHelper.getInstance().clearSP();
    }

    private static void logOutEvent() {
//        /**通知首页(MainActivity)登录退出动作,关闭MainActivity*/
//        LogoutEvent logoutEvent = new LogoutEvent();
//        logoutEvent.setAction(1);
//        EventBus.getDefault().post(logoutEvent);
    }

    private static final char[] hexCode = "0123456789ABCDEF".toCharArray();

    public static String md5(String input) {
        byte[] bytes = new byte[0];
        try {
            bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return printHexBinary(bytes);
    }

    public static String printHexBinary(byte[] data) {
        StringBuilder r = new StringBuilder(data.length * 2);
        for (byte b : data) {
            r.append(hexCode[(b >> 4) & 0xF]);
            r.append(hexCode[(b & 0xF)]);
        }
        return r.toString();
    }

    /**
     * 从父 view 中移除自己
     * @param child
     */
    public static void removeSelfFromParent(View child){
        if (child != null){
            ViewGroup parent = (ViewGroup)child.getParent();
            if (parent != null) {
                parent.removeView(child);
            }
        }
    }

}
